// packageK/my/my.js
const app = getApp()
const getInvite = require('../../mybehaviors/getInvite/getInvite');
const orderList = [
  {id: 1, text: '待付款', icon: '/image/icon/order-pay.png', status: '1'},
  {id: 2, text: '待发货', icon: '/image/icon/order-send.png', status: '2'},
  {id: 3, text: '待收货', icon: '/image/icon/order-received.png', status: '3'},
  // {id: 4, text: '待评价', icon: '/image/icon/order-evaluate.png', status: '4'},
  {id: 5, text: '退款售后', icon: '/image/icon/order-refund.png', status: '5'}
]
const serviceList = [
  {id: 1, text: '优惠券', icon: '/image/icon/service-coupon.png', link: '/packageD/coupon/coupon_store'},
  {id: 2, text: '足迹', icon: '/image/icon/service-footer.png', link: '/packageD/member/footprint/footprint'},
  {id: 3, text: '收藏', icon: '/image/icon/service-favorites.png', link: '/packageD/member/collection/collection'},
  {id: 4, text: '地址管理', icon: '/image/icon/service-address.png', link: '/packageD/member/addressList/addressList'},
  {id: 5, text: '积分商城', icon: '/image/icon/service-shop.png', link: '/packageG/newDiy/newDiy?page_id=3'},
  {id: 6, text: '我的积分', icon: '/image/icon/service-integral.png', link: '/packageB/member/integral/integral'},
  {id: 7, text: '完善资料', icon: '/image/icon/service-data.png', link: '/packageA/member/new_userinfo/new_userinfo'},
  {id: 8, text: '账号设置', icon: '/image/icon/service-setting.png', link: '/packageA/member/info/info'}
]
Page({
  behaviors: [getInvite],
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    defaultAvatar: '',
    orderList: [],
    serviceList,
    loginShow: false,
    // 兼容登录
    canIUseGetUserProfile: false,
    canIUseGetUserProfileTap: false,
    AuthorizedPhone: '',
    changidInfo: {
      uid: null,
      change_uid: null,
    },
    // 显示设置昵称头像弹窗,
    editMemberPopupShow: false
  },

  /**
   * 去登录
   */
  goLogin: function() {
    const { userInfo } = this.data
    if (!userInfo || !userInfo.nickname) {
      this.setData({ loginShow: true })
    } else {
      this.setData({ editMemberPopupShow: true })
    }
  },

  /**
   * 去修改昵称/头像
   */
  toEditAvatar(){
    wx.navigateTo({
      url: '/packageA/member/new_userinfo/new_userinfo',
    })
  },

  /**
   * 快捷登录点击-调取微信授权
   * @param {Object} e 
   */
  getUserProfileTap: function(e) {
    const { canIUseGetUserProfile, canIUseGetUserProfileTap } = this.data;
    if (canIUseGetUserProfileTap) return;
    this.setData({ canIUseGetUserProfileTap: true });
    const that = this;
    if (canIUseGetUserProfile) {
      wx.getUserProfile({
        desc: '获取用户信息',
        success: (_info) => {
          const info = {
            'nickName': _info.userInfo.nickName,
            'avatarUrl': "",
            'gender': _info.userInfo.gender
          };
          that.loginbtn(info);
        },
        fail: (err) => {
          app.tips(err.errMsg || 'getUserProfile登录失败，请联系管理员！')
          that.setData({ canIUseGetUserProfileTap: false });
        }
      })
    } else {
      app.tips('不支持的授权方式，请联系管理员！');
    }
  },

  /**
   * 获取授权后请求登录接口
   * @param {Object} _info 微信授权信息
   */
  loginbtn: function(_info) {
    const { logintap } = this.data
    // 正在请求 直接return
    if(logintap)  return;
    this.setData({ logintap: true });
    const that = this;
    wx.login({
      success: (_json) => {
        // wx.login登录成功，获取用户info
        if (_json.code) {
          wx.request({
            url: app.getNetAddresss("member.login.index"),
            header: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
            },
            data: {
              code: _json.code,
              info: _info,
              ver: '2',
              login_param: app.globalData.loginScene
            },
            success: function(res) {
              const { result, data, msg } = res.data
              setTimeout(() => {
                that.setData({
                  logintap: false
                });
              }, 1000);
              if (result == 1) {
                if (data.user_info) {
                  wx.setStorageSync("nickname", data.user_info.nickname);
                }
                if (msg.session) {
                  wx.setStorageSync('session', msg.session);
                }
                wx.setStorage({
                  key: "openid",
                  data: data.openid
                });
                if (msg.wx_token) {
                  wx.setStorageSync('wx_token', msg.wx_token);
                }
                if (_info) {
                  wx.setStorageSync('userInfo', _info);
                }
                wx.setStorage({
                  key: "yz_uid",
                  data: msg.uid
                });
                if (data.is_first_time_bind) {
                  // 首次授权登录自动绑定手机号
                  that.setData({
                    showAutoBindPhone: true
                  });
                } else {
                  that.getInvite();
                }
                // 登录之后清除首页缓存数据重新请求
                wx.removeStorageSync("new_decorate"); 
              } else {
                wx.showModal({
                  title: '提示',
                  content: _data.msg
                });
              }
            },
            fail: function(err) {
              that.setData({
                logintap: false,
                canIUseGetUserProfileTap: false
              });
              app.tips('第三方登录失败session、wx_token获取失败')
              console.log(err)
            }
          })
        } else {
          that.setData({
            logintap: false,
            canIUseGetUserProfileTap: false
          });
          app.tips('获取用户登录态失败！')
          console.log(_json.errMsg);
        }
      },
      fail: (err) => {
        app.tips('登录失败，请求被拒绝！获取用户登录态失败！')
        console.log(err)
      }
    })
  },

  /**
   * 是否开启邀请页面
   */
  getInvite() {
    let urlStr = app.getNetAddresss("member.member.isValidatePage");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let data = res.data;
          try {
            this.checktoInvite(data, 'member'); //定义在 behaviors里面
          } catch (e) {
            wx.reLaunch({
              url: "/packageK/my/my",
            });
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  // 获取授权手机号 ============= start =============
  /**
   * 获取授权手机号
   * @param {Object} e 
   */
  async getPhoneNumber(e) {
    let info = e.detail;
    if (info.errMsg == 'getPhoneNumber:ok') {
      let mobile = await this.getPhone_index(info.code);
      this.data.AuthorizedPhone = mobile;
      await this.getPrepBind(mobile);
      await this.setBindPhone();
      this.getInvite();
    } else {
      this.getInvite();
    }
  },

  getPhone_index(info) {
    wx.showLoading({
      title: '加载中',
    });
    let urlStr = app.getNetAddresss('member.member.miniMemberMobile');
    return new Promise((resolve, reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        validateBol: 2,
        data: {
          code: info,
          not_validate_page: '0'
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            resolve(res.data.phone_info.purePhoneNumber);
          } else {
            wx.hideLoading({
              success: (res) => {},
            });
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject();
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },

  /**
   * 先验证是否导致会员id变更
   * @param {Number | String } mobile 手机号
   */
  getPrepBind(mobile) {
    let urlStr = app.getNetAddresss("member.member.prepBind");
    return new Promise((resolve, reject) => {
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: {
          mobile: mobile,
          not_validate_page: '0'
        },
        validateBol: 2,
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            if (res.data.is_show) {
              // 显示 导致会员id变更 弹窗
              wx.hideLoading({
                success: (res) => {},
              });
              let basic_info = this.basic_info;
              this.setData({
                balance: wx.getStorageSync('balance'),
                point: wx.getStorageSync('integral'),
                showChangeID: true,
                changidInfo: {
                  uid: res.data.uid,
                  change_uid: res.data.change_uid
                }
              });
            } else {
              resolve();
            }
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
            reject(res);
          }
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },

  setBindPhone(e) {
    wx.hideLoading();
    let urlStr = app.getNetAddresss('member.member.bindMobile');
    return new Promise((resolve, reject) => {
      app._postNetWork({
        url: urlStr,
        data: {
          mobile: this.data.AuthorizedPhone,
          mini_first_time_bind: 1
        },
        success: (resdata) => {
          var res = resdata.data;

          if (this.data.changidInfo && this.data.changidInfo.change_uid) {
            // 更新uid为合并后的会员id
            wx.setStorage({
              key: "yz_uid",
              data: this.data.changidInfo.change_uid,
            });
          }

          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          this.getInvite();
          resolve();
        },
        fail: function (res) {
          reject(res);
        }
      });
    });
  },
  // 获取授权手机号 ============= end =============

  /**
   * 填写昵称/头像关闭
   * @param {Object} e detail包含头像/昵称
   */
  editMemberPopupClose: function(e) {
    const { name, avatar} = e.detail
    this.setData({
      'userInfo.nickname': name || '',
      'userInfo.avatar': avatar || '',
    })
  },

  /**
   * 获取页面数据
   */
  getPageData: function() {
    const urlStr = app.getNetAddresss('member.member.getUserInfo');
    const that = this;
    app._getNetWork({
      url: urlStr,
      data: { basic_info: 1 },
      success: function(res) {
        const { result, data, msg } = res.data
        if (result == 1) {
          that.setData({ userInfo: data })
          if (!data.avatar) {
            that.setData({ editMemberPopupShow: true })
          }
          let _orderList = orderList
          if (data.order && data.order.length) {
            _orderList.forEach(order => {
              let target = null;
              if (order.status == 1) {
                target = data.order.find(item => item.status == 0)
              } else if(order.status == 2) {
                target = data.order.find(item => item.status == 1)
              } else if(order.status == 3) {
                target = data.order.find(item => item.status == 2)
              } else if(order.status == 5) {
                target = data.order.find(item => item.status == 11)
              }
              order.total = target ? target.total : 0
            })
          }
          that.setData({
            orderList: _orderList
          })
        } else if(result == 0 && data.login_status == 0) {
          // 未登录状态
          that.setData({ loginShow: true })
        } else {
          app.tips(msg || '获取数据失败')
        }
      },
      complete: function() {
        wx.stopPullDownRefresh()
      }
    })
  },

  /**
   * 购买vip
   */
  buyVip: function() {
    wx.navigateTo({
      url: '/packageC/o2o/card/CardOpenMembership/CardOpenMembership',
    })
  },

  /**
   * 全部订单
   */
  gotoAllOrderList: function() {
    wx.navigateTo({
      url: '/packageA/member/myOrder_v2/myOrder_v2?orderType=shop&status=0',
    })
  },

  /**
   * 订单跳转
   * @param {Object} e 
   */
  gotoOrderList: function(e) {
    const { status } = e.currentTarget.dataset
    if (status == 5) {
      // 售后
      wx.navigateTo({
        url: '/packageD/member/myOrder/Aftersaleslist/Aftersaleslist',
      })
    } else if(status == 4) {

    } else {
      wx.navigateTo({
        url: '/packageA/member/myOrder_v2/myOrder_v2?orderType=shop&status=' + status,
      })
    }
  },

  /**
   * 服务于功能跳转
   * @param {Object} e 
   */
  serviceClick: function(e) {
    const { link } = e.currentTarget.dataset
    if (!link) {
      return
    }
    wx.navigateTo({
      url: link,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (wx.getUserProfile) {
      // 兼容pc小程序登录
      this.setData({
        canIUseGetUserProfile: true
      });
    }
    this.getPageData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getPageData()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})